<?php

require_once(Mage::getBaseDir('lib')."/Excel/PHPExcel.php");
require_once(Mage::getBaseDir('lib')."/Excel/PHPExcel/Writer/Excel2007.php");

class Silk_Zgb_Adminhtml_ExportController extends Mage_Adminhtml_Controller_Action
{
        protected function _isAllowed()
        {
            return true;
            return Mage::getSingleton('admin/session')->isAllowed('newsletter/inventory');
        }
	public function indexAction(){

	}

    public function categoryAction()
    {
        //echo Mage::getBaseDir('lib')."/Excel/PHPExcel.php";
        //echo "导出分类数据";

        $objPHPExcel  = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);

        $root = Mage::getModel('catalog/category')->load(12);
        $categorys = $root->getChildrenCategories();

        $shidx = 0;
        foreach($categorys as $category)
        {
            if($shidx != 0) $objPHPExcel->createSheet();
            $objPHPExcel->setActiveSheetIndex($shidx);
            $sheet = $objPHPExcel->getActiveSheet();
            $sheet->setTitle($category->getName());
            $sheet->getColumnDimension('B')->setWidth(12);
            $sheet->getColumnDimension('C')->setWidth(50);

            $products = $category->getProductCollection();

            $row = 1;
            foreach($products as $product)
            {
                if($row==1)
                {
                    $sheet->setCellValue("A{$row}","编号");
                    $sheet->setCellValue("B{$row}","SKU");
                    $sheet->setCellValue("C{$row}","名称");
                    $sheet->setCellValue("D{$row}","价格");
                }
                else
                {
                    $product = Mage::getModel('catalog/product')->load($product->getId());
                    $sheet->setCellValue("A{$row}",$product->getId());
                    $sheet->setCellValue("B{$row}",$product->getSku());
                    $sheet->setCellValue("C{$row}",$product->getName());
                    $sheet->setCellValue("D{$row}",$product->getPrice());
                }
                $row++;
            }

            $shidx++;
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="分类数据.xlsx"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
}
